package com.aifast.common.dict;

import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;

/**
 * @Author fujian
 * @since 2022/9/9 11:31
 */
public class DictBindSerializer extends JsonSerializer<Object>  implements ContextualSerializer {

    private DictBindType type;
    private DictBind dictBind;


    public DictBindSerializer(){
    }

    public DictBindSerializer(DictBind db){
        this.dictBind = db;
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
//        Console.log(dictBind);
//        Console.log(gen.getOutputContext().getCurrentName());
//        Console.log(value);
//        Console.log(gen.getOutputContext().getCurrentValue());
        gen.writeObject(value);
        gen.writeFieldName(DictBindTranslator.genTargetFieldName(gen.getOutputContext().getCurrentName(),dictBind.target()));
        gen.writeObject(DictBindTranslator.genTargetFieldValue(dictBind,value));

    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        DictBind annotation = property.getAnnotation(DictBind.class);
        if(ObjectUtil.isNotNull(annotation)){
            this.dictBind = annotation;
            return this;
        }
        return prov.findValueSerializer(property.getType(), property);
    }


}
